package cn.bdqn.sptparent.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class JSONUtil {
    /**
     * List集合转换json
     * @param list
     * @return
     * @param <T>
     */
    public static<T> String storeUsersInRedis(List<T> list) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "";
        try {
            jsonString = objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    /**
     * json转换List<T>
     * @param jsonString
     * @return
     * @param <T>
     */
    public static  <T>  List<T> retrieveUsersFromRedis(String jsonString) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<T> users = objectMapper.readValue(jsonString, new TypeReference<List<T>>() {});
            return users;
        } catch (IOException e) {
            e.printStackTrace();
            return null; // 或者抛出一个更合适的异常
        }
    }
}
